package com.banksoft.front.controller;

import com.banksoft.admin.SystemCache;
import com.banksoft.admin.bean.AmountType;
import com.banksoft.admin.bean.MemberType;
import com.banksoft.admin.bean.OrderStatus;
import com.banksoft.admin.dao.PartnerApplyDao;
import com.banksoft.admin.dao.UserDao;
import com.banksoft.admin.entity.*;
import com.banksoft.admin.service.*;
import com.banksoft.common.BaseController;
import com.banksoft.common.ConfigHelper;
import com.banksoft.front.bean.WeiXinUser;
import com.banksoft.front.util.WeixinUtil;
import com.banksoft.front.util.WxSupportUtil;
import com.banksoft.util.DateUtil;
import com.banksoft.util.QrCodeUtil;
import com.banksoft.util.StringNumber;
import com.banksoft.util.StringUtil;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

/**
 * Created by vanjoger on 2017/1/9.
 */
@Controller
@RequestMapping("/front/user")
public class FrontUserController extends BaseController{

    @Autowired
    BaseService baseService;
    @Autowired
    UserService userService;
    @Autowired
    PartnerApplyService partnerApplyService;
    @Autowired
    OrderService orderService;
    @Autowired
    UserMoneyService userMoneyService;
    @Autowired
    AmoutLogService amoutLogService;
    @Autowired
    UserAddressService userAddressService;

    @RequestMapping("/main")
    public String main(HttpServletRequest request, Model model, HttpServletResponse response){
        User user = (User) request.getSession().getAttribute(SystemCache.SESSION_USER);
        //再查一遍数据库 防止用户升级
        user = baseService.findById(UserDao.class,user.getId());
        //if(!StringUtil.isNotNull(user.getHeadimgUrl())||(StringUtil.isNotNull(user.getHeadimgUrl())&&!user.getHeadimgUrl().startsWith("http://"))){//有时候头像没有加载出来 重新获取一遍
            try {//实时拉取用户信息 刷新头像
                WeiXinUser  weiXinUser = WxSupportUtil.getWeiXinUser(user.getOpenId(), SystemCache.getWxSetting());
                if(weiXinUser!=null) {
                    user.setNickName(weiXinUser.getNickname());
                    user.setSex(weiXinUser.getSex());
                    user.setCountry(weiXinUser.getCountry());
                    user.setProvince(weiXinUser.getProvince());
                    if (StringUtil.isNotNull(weiXinUser.getHeadimgurl()))
                        user.setHeadimgUrl(weiXinUser.getHeadimgurl());
                    user.setCity(weiXinUser.getCity());
                    try {
                        this.baseService.update(UserDao.class, user);
                    } catch (Exception e) {
                        e.printStackTrace();
                        user.setNickName("");
                        this.baseService.update(UserDao.class, user);
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        //}
        request.getSession().setAttribute(SystemCache.SESSION_USER,user);
        model.addAttribute("user",user);

        UserMoney money = this.userMoneyService.findByUserId(user.getId());
        String total = "0";
        if(money!=null) {
            total = StringNumber.add(money.getCash(), money.getBonus());
            model.addAttribute("money", total);
            if(StringNumber.compareTo(money.getTotalAmount(),total)>0){
                model.addAttribute("total",money.getTotalAmount());
            }else{
                model.addAttribute("total",total);
            }
        }
        try {
            Long startDate = DateUtil.getLongFormStrDate(DateUtil.getFormatDate(new Date(), "yyyy-MM-dd") + " 00:00:00");
            Long endDate = DateUtil.getLongFormStrDate(DateUtil.getFormatDate(new Date(), "yyyy-MM-dd") + " 23:59:59");
            Map map = new HashMap();
            map.put("startDate", startDate);
            map.put("endDate", endDate);
            map.put("userId", user.getId());
            String[] types =new String[]{AmountType.GoldFee.name(),AmountType.GeneralFee.name(),AmountType.PartnerFee.name(),AmountType.FxFee.name()};
            map.put("type",types);

            //我的流水
            List<AmountLog> amountLogList = this.amoutLogService.query(map);
            String todayAmount = "0";
            if(StringUtil.isNotEmpty(amountLogList)){
                for(AmountLog log:amountLogList){
                    if(StringUtil.isNotNull(log.getCash()))
                        todayAmount = StringNumber.add(todayAmount,log.getCash());
                    if(StringUtil.isNotNull(log.getBonus()))
                        todayAmount = StringNumber.add(todayAmount,log.getBonus());
                }
            }
            model.addAttribute("amountSize",todayAmount);
            //我的订单
            map.put("openId",user.getOpenId());
            map.put("type","0");
            List<Order> orderList = this.orderService.query(map);
            model.addAttribute("orderSize",orderList!=null?orderList.size():0);

        }catch (Exception e){
            e.printStackTrace();
        }


        return "front/user_center";
    }

    @RequestMapping("/loadAllOrder")
    @ResponseBody
    public JSONObject loadAllOrder(HttpServletRequest request){
        try{
            User user = (User) request.getSession().getAttribute(SystemCache.SESSION_USER);
            int total = getCnt(user,0);

            return this.FmtResult(true,null,total);
        }catch (Exception e){
            e.printStackTrace();
        }
        return this.FmtResult(false,null,null);
    }

    private int getCnt(User user,int total) {
        List<Order> orders = this.orderService.listByUserIds(new String[]{user.getId()});
        int cnt = orders!=null?orders.size():0;
        total += cnt;
        if(cnt>0)
            System.out.println(user.getAccount()+":"+user.getNickName()+" ---  "+cnt);
        List<User> list = this.userService.listByRecommendId(user.getId());
        if(StringUtil.isNotEmpty(list)){
            for(User u:list){
                if(!user.getId().equals(u.getId()))//防止推荐人是自己的情况下 出现的死循环
                    total = getCnt(u,total);
            }
        }
        return total;
    }

    @RequestMapping("/loadNewOrder")
    @ResponseBody
    public JSONObject loadNewOrder(HttpServletRequest request){
        try{
            User user = (User) request.getSession().getAttribute(SystemCache.SESSION_USER);
            int total = getNewOrderCnt(user,0);

            return this.FmtResult(true,null,total);
        }catch (Exception e){
            e.printStackTrace();
        }
        return this.FmtResult(false,null,null);
    }

    private int getNewOrderCnt(User user,int total) {
        String startDate = DateUtil.getFormatDate(new Date(),"yyyy-MM-dd")+" 00:00:00";
        String endDate = DateUtil.getFormatDate(new Date(),"yyyy-MM-dd")+" 23:59:59";
        Map map = new HashMap();
        map.put("startDate",DateUtil.getLongFormStrDate(startDate));
        map.put("endDate",DateUtil.getLongFormStrDate(endDate));
        map.put("type","0");//普通订单
        map.put("status",new String[]{OrderStatus.Pay.name(),OrderStatus.Send.name(),OrderStatus.Suc.name()});
        map.put("ids",new String[]{user.getId()});

        List<Order> orders = this.orderService.count(map);

        int cnt = orders!=null?orders.size():0;
        total += cnt;
        if(cnt>0)
            System.out.println(user.getAccount()+":"+user.getNickName()+" ---  "+cnt);
        List<User> list = this.userService.listByRecommendId(user.getId());
        if(StringUtil.isNotEmpty(list)){
            for(User u:list){
                if(!user.getId().equals(u.getId()))//防止推荐人是自己的情况下 出现的死循环
                    total = getNewOrderCnt(u,total);
            }
        }
        return total;
    }


    /**
     * 生成二维码图片
     * @param user
     * @param request
     */
    private void generalImg(User user,HttpServletRequest request) {
        if(!StringUtil.isNotNull(user.getImg())) {
            String filePath = ConfigHelper.GetInstance().GetConfig("Upload_Path") + "/qrcode/" + DateUtil.getFormatDate(new Date(), "yyyyMMdd") + "/" + System.currentTimeMillis() + ".png";
            String file = getFilePath(filePath, request);

            String domain = getDomain(request);
            String url = domain + "/wx/index?state=" + user.getId();
            try {
                QrCodeUtil.encodeQrCodeToFile(url, file);
                user.setImg(filePath);
                this.baseService.update(UserDao.class, user);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @RequestMapping("/beforeUpdate")
    public String beforeUpdate(HttpServletRequest request,Model model){
       /* String openId = this.getCookie(SystemCache.SESSION_USER,request);
        User user = this.userService.findByOpenId(openId);*/
        User user = (User) request.getSession().getAttribute(SystemCache.SESSION_USER);
        model.addAttribute("user",user);

        String province = "";
        String  city = "";
        String area = "";
        List<UserAddress> userAddressList = userAddressService.listByUserId(user.getId());
        UserAddress address = null;
        if(StringUtil.isNotEmpty(userAddressList)){
             address = userAddressList.get(0);
        }else{
            address = new UserAddress();
            address.setTelephone(user.getMobile());
        }
        if(StringUtil.isNotNull(user.getUserArea())){
            province = user.getUserProvince();
            city = user.getUserCity();
            area = user.getUserArea();
        }else{
            if(address!=null){
                province = address.getProvince();
                city = address.getCity();
                area = address.getArea();
            }
        }
        model.addAttribute("userAddress",address);
        model.addAttribute("province",province);
        model.addAttribute("city",city);
        model.addAttribute("area",area);

        UserMoney money = userMoneyService.findByUserId(user.getId());
        model.addAttribute("money",StringNumber.add(money.getCash(),money.getBonus()));
        return "front/user_update";

    }

    @RequestMapping("/update")
    @ResponseBody
    public JSONObject update(String type,String userName,String telephone,String idCard,String bankName,String cardName,String cardNo,String userLevel,String province,String city,String area,String provinceName,
                             String cityName,String areaName,String amount,String address,HttpServletRequest request,String addressProvince,String addressProvinceName,String addressCity,String addressCityName,String addressArea,String addressAreaName){
        try{
            User user = (User) request.getSession().getAttribute(SystemCache.SESSION_USER);
            if(type.equals(MemberType.Partner.name())){
                List<User> list = this.userService.listUserByCity(userLevel,province,city,area);
                if(StringUtil.isNotEmpty(list))
                    return this.FmtResult(false,"您申请代理的区域已被其他人代理，请重新选择",null);

                this.partnerApplyService.saveParnterApply(user.getId(),"",province,provinceName,city,cityName,area,areaName,userLevel,userName,telephone,idCard,bankName,cardName,cardNo,addressProvince,addressProvinceName,addressCity,addressCityName,addressArea,addressAreaName);
                return this.FmtResult(true,"您的升级申请已经提交，请与相关人员联系！",null);
            }else{
                //保存升级订单
                JSONObject json = this.orderService.saveSjOrder(type,"",user.getId(),province,provinceName,city,cityName,area,areaName,amount,userName,telephone,idCard,bankName,cardName,cardNo,addressProvince,addressProvinceName,addressCity,addressCityName,addressArea,addressAreaName, address);
                return json;
            }
        }catch (Exception e){
            e.printStackTrace();
            return this.FmtResult(false,"操作失败",null);
        }
    }

    @RequestMapping("updatePay")
    public String updatePay(String orderId,Model model){
        model.addAttribute("suc",true);
        model.addAttribute("orderId",orderId);
        return "front/order_getAuth";
    }

    @RequestMapping("/money")
    public String money(HttpServletRequest request,Model model){
        try {
            User user = (User) request.getSession().getAttribute(SystemCache.SESSION_USER);
            UserMoney money = this.userMoneyService.findByUserId(user.getId());
            model.addAttribute("user", user);
            model.addAttribute("money",money);
        }catch (Exception e){
            e.printStackTrace();
        }
        return "front/front_amount_detail";
    }


    @RequestMapping("/info")
    public String info(HttpServletRequest request,Model model){
        User user = (User) request.getSession().getAttribute(SystemCache.SESSION_USER);
        if(StringUtil.isNotNull(user.getRecommendId())){
            User upuser = this.baseService.findById(UserDao.class,user.getRecommendId());
            if(upuser!=null){
                if(StringUtil.isNotNull(upuser.getCardName())){//真实姓名存在
                    user.setTdyj(upuser.getCardName());
                }else{
                    List<UserAddress> userAddressList = this.userAddressService.listByUserId(user.getRecommendId());
                    if(StringUtil.isNotEmpty(userAddressList)){//收货人存在
                        UserAddress address = userAddressList.get(0);
                        user.setTdyj(address.getUserName());
                    }else{//收货人不存在
                        user.setTdyj(upuser.getNickName()+"("+upuser.getAccount()+")");
                    }
                }
            }
        }
        if(!StringUtil.isNotNull(user.getHeadimgUrl())){
            user.setHeadimgUrl("/resources/images/noavatar.gif");
        }
        model.addAttribute("user",user);
        return "front/user_info";
    }

    @RequestMapping("/updateInfo")
    @ResponseBody
    public JSONObject updateInfo(String nickName,String sex,String mobile,String birthday,String cardName,String bankName,String cardNo,
                                 String idCard,HttpServletRequest request){
        try{
            User user = (User) request.getSession().getAttribute(SystemCache.SESSION_USER);
            if(user!=null){//防止其他信息变化  重新抓取信息
                user = this.baseService.findById(UserDao.class, user.getId());
                user.setNickName(nickName);
                user.setSex(sex);
                user.setMobile(mobile);
                user.setBirthday(birthday);
                user.setCardName(cardName);
                user.setBankName(bankName);
                user.setCardNo(cardNo);
                user.setIdCard(idCard);
                this.baseService.update(UserDao.class,user);
                return this.FmtResult(true,"修改成功",null);
            }
            return this.FmtResult(false,"没有找到用户信息，请重新打开！",null);
        }catch (Exception e){
            e.printStackTrace();
        }
        return this.FmtResult(false,"保存信息出错了！",null);
    }

    @RequestMapping("/getInfo")
    @ResponseBody
    public JSONObject getInfo(HttpServletRequest request){
       try {
           User user = (User) request.getSession().getAttribute(SystemCache.SESSION_USER);
           user = this.baseService.findById(UserDao.class, user.getId());
           if(!StringUtil.isNotNull(user.getIsMember())||!"1".equals(user.getIsMember()))
                return this.FmtResult(true,"下单分享后可享受返现奖励",null);
       }catch (Exception e){
           e.printStackTrace();
       }
       return this.FmtResult(false,null,null);
    }


    @RequestMapping("/getTxAmount")
    @ResponseBody
    public JSONObject getTxAmount(String amount){
        try{
            String txFee = ConfigHelper.GetInstance().GetConfig("TxFee");
            String d = StringNumber.sub(amount,StringNumber.div(StringNumber.mul(amount,txFee),"1000"));
            return this.FmtResult(true,null,d);
        }catch (Exception e){
            e.printStackTrace();
        }
        return this.FmtResult(false,null,null);

    }

    @RequestMapping("/checkQydl")
    @ResponseBody
    public JSONObject checkQydl(String userLevel,String province,String city,String area){
        try{
            List<User> list = this.userService.listUserByCity(userLevel,province,city,area);
            if(StringUtil.isNotEmpty(list))
                return this.FmtResult(false,"您申请代理的区域已被其他人代理，请重新选择",null);
        }catch (Exception e){
            e.printStackTrace();
        }
        return this.FmtResult(true,null,null);
    }
}
